<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\utils\enum\ServiceState;
use support\Request;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Exception;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageMchBill;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageOrdersAddress;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageService;
use plugin\ycMassage\app\model\MassageShopStatistics;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserAgent;
use plugin\ycMassage\app\model\MassageUserChannels;
use plugin\ycMassage\app\model\MassageUserDealer;
use plugin\ycMassage\app\model\MassageUserFreezeMoney;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianBill;
use plugin\ycMassage\app\model\MassageUserTechnicianService;
use plugin\ycMassage\app\model\MassageUserTechnicianStatistics;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\app\model\MassageUserWechat;
use plugin\ycMassage\app\model\MassageWinnerlookPrivacy;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\enum\WinnerlookChannels;
use plugin\ycMassage\utils\enum\WinnerlookState;
use plugin\ycMassage\utils\notice\Notice;
use plugin\ycMassage\utils\Rsa;
use plugin\ycMassage\utils\Yunxin;
use think\facade\Db;

class AppointmentServiceController extends BaseController {
    public function user(Request $request) {
        $uid = $request->uid;
        $where = [
            ['uas.uid', '=', $uid],
            [
                'uas.state',
                'in',
                [
                    ServiceState::WAIT_START['value'],
                    ServiceState::TRAVELING['value'],
                    ServiceState::ARRIVAL['value'],
                    ServiceState::ING['value'],
                ]
            ],
            [
                'o.state',
                'in',
                [
                    OrdersState::WAIT_START['value'],
                    OrdersState::SERVICE_ING['value']
                ]
            ]
        ];
        $field = [
            'uas.*',
            'u.nickname,u.headimg',
            's.title'
        ];
        $model = MassageAppointmentService::alias('uas')->where($where);
        $model->join('massage_user u', 'u.id=uas.technician_id');
        $model->join('massage_service s', 's.id=uas.service_id');
        $model->join('massage_orders o', 'o.id=uas.orders_id');
        $model->field($field);
        $list = $model->select()->each(function ($item) {
        });
        if ($list->isEmpty()) {
            return $this->fail('没有预约');
        }
        return $this->successRes($list);
    }
    public function technician(Request $request) {
        $uid = $request->uid;
        $where = [
            ['uas.technician_id', '=', $uid],
            [
                'uas.state',
                'in',
                [
                    ServiceState::WAIT_START['value'],
                    ServiceState::TRAVELING['value'],
                    ServiceState::ARRIVAL['value'],
                    ServiceState::ING['value'],
                ]
            ],
            [
                'o.state',
                'in',
                [
                    OrdersState::WAIT_START['value'],
                    OrdersState::SERVICE_ING['value']
                ]
            ]
        ];
        $field = [
            'uas.*',
            'u.nickname,u.headimg',
            's.title'
        ];
        $model = MassageAppointmentService::alias('uas')->where($where);
        $model->join('massage_user u', 'u.id=uas.uid');
        $model->join('massage_service s', 's.id=uas.service_id');
        $model->join('massage_orders o', 'o.id=uas.orders_id');
        $model->field($field);
        $list = $model->select()->each(function ($item) {
            $item->is_start = 0;
            if ($item->start_time < date('Y-m-d H:i:s')) {
                $item->is_start = 1;
            }
        });
        if ($list->isEmpty()) {
            return $this->fail('没有预约');
        }
        return $this->successRes($list);
    }
    public function details(Request $request) {
        $id = $request->get('id');
        $action = $request->get('action');
        $uid = $request->uid;
        $where = [
            ['uas.id', '=', $id],
            ['uas.saas_appid', '=', $request->saas_appid]
        ];
        if ($action === 'user') {
            $where[] = ['uas.uid', '=', $uid];
        } else {
            $where[] = ['uas.technician_id', '=', $uid];
        }
        $field = [
            'uas.*,uas.duration as service_duration',
            'u.nickname,u.headimg,u.mobile as user_mobile',
            't.nickname as technician_nickname,t.headimg as technician_headimg,t.mobile as technician_mobile,technician.work_shop_id',
            's.thumb,s.title,s.overtime_separate,s.overtime_price,s.price,s.tips,s.overtime_duration,s.overtime_state,s.overtime_separate',
            's.sales_num + s.virtually_sales_num as sales_num',
            'o.trade,o.remark,o.state as orders_state',
            'os.price,os.num',
            'oa.province,oa.city,oa.area,oa.street,oa.address_detail,oa.name,oa.mobile,oa.latitude,oa.longitude',
            'shop.id as shop_id,shop.title as shop_title,shop.logo as shop_logo,shop.province as shop_province,shop.city as shop_city,shop.area as shop_area,shop.street as shop_street,shop.address as shop_address,shop.longitude as shop_longitude,shop.latitude as shop_latitude'
        ];
        $model = MassageAppointmentService::alias('uas')->where($where);
        $model->join('massage_user u', 'u.id=uas.uid');
        $model->join('massage_user t', 't.id=uas.technician_id');
        $model->join('massage_user_technician technician', 'technician.uid=t.id');
        $model->join('massage_service s', 's.id=uas.service_id');
        $model->join('massage_orders_sub os', 'os.id=uas.orders_sub_id');
        $model->join('massage_orders o', 'o.id=uas.orders_id');
        $model->join('massage_orders_address oa', 'oa.orders_id=o.id', 'LEFT');
        $model->join('massage_shop shop', 'shop.id=technician.work_shop_id', 'LEFT');
        $model->field($field);
        $Find = $model->find();
        if (!$Find) {
            return $this->fail('服务不存在');
        }
        if ($Find->state === ServiceState::NOT_PAY['value']) {
            return $this->fail('该服务还未支付');
        }
        $Find->technician_nickname = base64_decode($Find->technician_nickname);
        if (strpos($Find->headimg, 'http') !== 0) {
            $Find->headimg = UploadService::url($Find->headimg);
        }
        if (strpos($Find->technician_headimg, 'http') !== 0) {
            $Find->technician_headimg = UploadService::url($Find->technician_headimg);
        }
        if ($Find->shop_logo) {
            $Find->shop_logo = UploadService::url($Find->shop_logo);
        }
        $Find->thumb = UploadService::url($Find->thumb);
        if ($Find->arrival_time && $Find->departure_time) {
            $Find->commuting_time = strtotime($Find->arrival_time) - strtotime($Find->departure_time);
        }
        if ($action === 'user') {
            $builder = Builder::create()
                ->writer(new PngWriter())
                ->writerOptions([])
                ->data($this->getTechnicianVerification($request, $Find->id))
                ->encoding(new Encoding('UTF-8'))
                ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                ->size(400)
                ->margin(10)
                ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
                ->validateResult(false);
            $result = $builder->build();
            $Find->qrcode = $result->getDataUri();
            $Find->url = $this->getTechnicianVerification($request, $Find->id);
        }
        if ($Find->technician_mobile) {
            $Find->technician_mobile = substr_replace($Find->technician_mobile, '****', 3, 4);
        }
        if ($Find->mobile) {
            $Find->mobile = substr_replace($Find->mobile, '****', 3, 4);
        } else {
            $Find->mobile = substr_replace($Find->user_mobile, '****', 3, 4);
        }

        $sub_orders = MassageOrdersSub::alias('os')
            ->join('massage_orders o', 'o.id=os.orders_id')
            ->join('massage_service s', 's.id=os.service_id')
            ->where([
                ['os.appointment_service_id', '=', $id],
                ['os.saas_appid', '=', $request->saas_appid]
            ])
            ->field([
                'o.id',
                'o.trade',
                'o.title',
                'o.price',
                'o.state',
                'o.num',
                'o.pay_time',
                'o.create_time',
                'o.remark',
                's.service_duration'
            ])
            ->select();
        $Find->sub_orders = $sub_orders;
        return $this->successRes($Find);
    }
    private function getTechnicianVerification(Request $request, $id) {
        $code = urlencode(Rsa::encryptNumber($id));
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        return $domain . "/app/ycMassage/#/technician/pages/index/verification?appid={$request->saas_appid}&code={$code}";
    }
    public function departure(Request $request) {
        $id = $request->post('id');
        $latitude = $request->post('latitude');
        $longitude = $request->post('longitude');
        $uid = $request->uid;
        $where = [
            ['id', '=', $id],
            ['saas_appid', '=', $request->saas_appid],
            ['technician_id', '=', $uid]
        ];
        Db::startTrans();
        try {
            if (MassageAppointmentService::where([
                'saas_appid' => $request->saas_appid,
                'technician_id' => $uid
            ])->whereIn('state', [
                ServiceState::TRAVELING['value'],
                ServiceState::ARRIVAL['value'],
                ServiceState::ING['value']
            ])->count()) {
                throw new \Exception('���先结束上一个服务');
            }
            $model = MassageAppointmentService::where($where)->find();
            if (!$model) {
                throw new \Exception('服务不存在');
            }
            if ($model->state != ServiceState::WAIT_START['value']) {
                throw new \Exception('服务状态异常,请刷新查看');
            }
            $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $model->orders_id])->select();
            foreach ($MassageAppointmentService as $item) {
                $item->state = ServiceState::TRAVELING['value'];
                $item->departure_time = date('Y-m-d H:i:s');
                $item->save();
            }
            $MassageOrders = MassageOrders::where(['id' => $model->orders_id])->find();
            if ($MassageOrders->state !== OrdersState::WAIT_START['value']) {
                throw new \Exception('订单状态异常,请刷新查看');
            }
            $MassageOrders->state = OrdersState::SERVICE_ING['value'];
            $MassageOrders->save();
            $MassageOrdersSub = MassageOrdersSub::where(['orders_id' => $MassageOrders->id])->select();
            foreach ($MassageOrdersSub as $item) {
                $item->state = OrdersState::SERVICE_ING['value'];
                $item->save();
            }
            if ($latitude && $longitude) {
                # 技师
                $MassageUserTechnician = MassageUserTechnician::where(['uid' => $model->technician_id])->find();
                $MassageUserTechnician->latitude = $latitude;
                $MassageUserTechnician->longitude = $longitude;
                $MassageUserTechnician->save();
            }
            # 将路费的一半转给技师
            if ($MassageOrders->travel_price > 0) {
                $remarks = "订单：{$MassageOrders->trade} - 去程路费";
                $commission = round($MassageOrders->travel_price / 2, 2);
                MassageUserTechnicianBill::increase($remarks, $model->technician_id, $commission, $model->uid);
            }
            $notice = new Notice();
            $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $model->orders_id])->find();
            $MassageUser = MassageUser::where(['id' => $model->uid])->find();
            $name = $MassageUser->nickname . '(' . $model->uid . ')';
            if ($MassageOrdersAddress) {
                $name = $MassageOrdersAddress['name'] . '(' . $model->uid . ')';
                $notice->addUSER($MassageOrdersAddress->mobile, null);
            }
            $MassageUserWechat = MassageUserWechat::where(['uid' => $model->uid])->find();
            if ($MassageUserWechat) {
                $notice->addUSER(null, $MassageUserWechat->openid);
            }
            $MassageUserT = MassageUser::alias('u')->where(['u.id' => $model->technician_id])
                ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                ->field('u.nickname,u.mobile,uw.openid')
                ->find();
            if ($MassageUserT) {
                $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
            }
            $MassageService = MassageService::where(['id' => $model->service_id])->find();
            $notice->saas_appid = $model->saas_appid;
            $notice->type = NoticeType::TECHNICIAN_DEPARTURE['value'];
            $notice->setData([
                'state' => ServiceState::TRAVELING['text'],
                'title' => $MassageService->title,
                'trade' => $MassageOrders->trade,
                'as_id' => $model->id,
                'name' => $name,
                'technician' => $MassageUserT->nickname . '(' . $model->technician_id . ')',
            ]);
            $notice->send();
            Db::commit();
            return $this->success('操作成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function arrival(Request $request) {
        $id = $request->post('id');
        $latitude = $request->post('latitude');
        $longitude = $request->post('longitude');
        $arrival_photo = $request->post('arrival_photo');
        $uid = $request->uid;
        $where = [
            ['id', '=', $id],
            ['saas_appid', '=', $request->saas_appid],
            ['technician_id', '=', $uid]
        ];
        Db::startTrans();
        try {
            $model = MassageAppointmentService::where($where)->find();
            if (!$model) {
                throw new \Exception('服务不存在');
            }
            if ($model->state != ServiceState::TRAVELING['value']) {
                throw new \Exception('服务状态异常,请刷新查看');
            }
            $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $model->orders_id])->select();
            $verification = State::NO['value'];
            if (getHpConfig('scan_qrcode_verification', (int)$request->saas_appid, 'orders')) {
                $verification = State::YES['value'];
            }
            if (getHpConfig('arrival_photo', (int)$request->saas_appid, 'orders')) {
                if (!$arrival_photo) {
                    throw new \Exception('请上传到达照片');
                }
                $arrival_photo = UploadService::path($arrival_photo);
            } else {
                $arrival_photo = null;
            }
            foreach ($MassageAppointmentService as $item) {
                $item->state = ServiceState::ARRIVAL['value'];
                $item->arrival_time = date('Y-m-d H:i:s');
                $item->verification = $verification;
                if ($verification == State::YES['value']) {
                    $item->verification_time = date('Y-m-d H:i:s');
                    $item->commuting_time = strtotime($item->arrival_time) - strtotime($item->departure_time);
                }
                if ($arrival_photo) {
                    $item->arrival_photo = $arrival_photo;
                }
                $item->save();
            }
            $MassageOrders = MassageOrders::where(['id' => $model->orders_id])->find();
            $MassageOrders->state = OrdersState::SERVICE_ING['value'];
            $MassageOrders->save();
            $MassageOrdersSub = MassageOrdersSub::where(['orders_id' => $MassageOrders->id])->select();
            foreach ($MassageOrdersSub as $item) {
                $item->state = OrdersState::SERVICE_ING['value'];
                $item->save();
            }
            if ($latitude && $longitude) {
                # 技师
                $MassageUserTechnician = MassageUserTechnician::where(['uid' => $model->technician_id])->find();
                $MassageUserTechnician->latitude = $latitude;
                $MassageUserTechnician->longitude = $longitude;
                $MassageUserTechnician->save();
            }
            # 将路费的一半转给技师
            if ($MassageOrders->travel_price > 0) {
                $remarks = "订单：{$MassageOrders->trade} - 返程路费";
                $commission = round($MassageOrders->travel_price / 2, 2);
                MassageUserTechnicianBill::increase($remarks, $model->technician_id, $commission, $model->uid);
            }
            $notice = new Notice();
            $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $model->orders_id])->find();
            $MassageUser = MassageUser::where(['id' => $model->uid])->find();
            $name = $MassageUser->nickname . '(' . $model->uid . ')';
            if ($MassageOrdersAddress) {
                $name = $MassageOrdersAddress['name'] . '(' . $model->uid . ')';
                $notice->addUSER($MassageOrdersAddress->mobile, null);
            }
            $MassageUserWechat = MassageUserWechat::where(['uid' => $model->uid])->find();
            if ($MassageUserWechat) {
                $notice->addUSER(null, $MassageUserWechat->openid);
            }
            $MassageUserT = MassageUser::alias('u')->where(['u.id' => $model->technician_id])
                ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                ->field('u.nickname,u.mobile,uw.openid')
                ->find();
            if ($MassageUserT) {
                $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
            }
            $MassageService = MassageService::where(['id' => $model->service_id])->find();
            $notice->saas_appid = $model->saas_appid;
            $notice->type = NoticeType::TECHNICIAN_ARRIVAL['value'];
            $notice->setData([
                'state' => ServiceState::ARRIVAL['text'],
                'title' => $MassageService->title,
                'trade' => $MassageOrders->trade,
                'as_id' => $model->id,
                'name' => $name,
                'technician' => $MassageUserT->nickname . '(' . $model->technician_id . ')',
            ]);
            $notice->send();
            Db::commit();
            return $this->success('操作成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function verification(Request $request) {
        $code = $request->post('code');
        $id = Rsa::decryptNumber($code);
        $uid = $request->uid;
        $where = [
            ['id', '=', $id],
            ['saas_appid', '=', $request->saas_appid],
            ['technician_id', '=', $uid]
        ];
        $model = MassageAppointmentService::where($where)->find();
        if ($model) {
            if (!$model->verification) {
                $model->verification = State::YES['value'];
                $model->verification_time = date('Y-m-d H:i:s');
                $MassageOrders = MassageOrders::where(['id' => $model->orders_id])->find();
                $notice = new Notice();
                $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $model->orders_id])->find();
                $MassageUser = MassageUser::where(['id' => $model->uid])->find();
                $name = $MassageUser->nickname . '(' . $model->uid . ')';
                if ($MassageOrdersAddress) {
                    $notice->addUSER($MassageOrdersAddress->mobile, null);
                    $name = $MassageOrdersAddress['name'] . '(' . $model->uid . ')';
                }
                $MassageUserWechat = MassageUserWechat::where(['uid' => $model->uid])->find();
                if ($MassageUserWechat) {
                    $notice->addUSER(null, $MassageUserWechat->openid);
                }
                $MassageUserT = MassageUser::alias('u')->where(['u.id' => $model->technician_id])
                    ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                    ->field('u.nickname,u.mobile,uw.openid')
                    ->find();
                if ($MassageUserT) {
                    $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
                }
                $MassageService = MassageService::where(['id' => $model->service_id])->find();
                $notice->saas_appid = $model->saas_appid;
                $notice->type = NoticeType::TECHNICIAN_VERIFICATION['value'];
                $notice->setData([
                    'state' => '已核验',
                    'title' => $MassageService->title,
                    'trade' => $MassageOrders->trade,
                    'as_id' => $model->id,
                    'name' => $name,
                    'technician' => $MassageUserT->nickname . '(' . $model->technician_id . ')',
                ]);
                $notice->send();
            }
            $model->commuting_time = strtotime($model->arrival_time) - strtotime($model->departure_time);
            if ($model->save()) {
                return $this->successRes($model);
            }
            return $this->fail('核验失败，请重试');
        }
        return $this->fail('服务不存在');
    }
    public function startService(Request $request) {
        $id = $request->post('id');
        $latitude = $request->post('latitude');
        $longitude = $request->post('longitude');
        $service_start_photo = $request->post('service_start_photo');
        $uid = $request->uid;
        $where = [
            ['id', '=', $id],
            ['saas_appid', '=', $request->saas_appid],
            ['technician_id', '=', $uid]
        ];
        Db::startTrans();
        try {
            $model = MassageAppointmentService::where($where)->find();
            if (!$model) {
                throw new \Exception('服务不存在');
            }
            if (MassageAppointmentService::where([
                'saas_appid' => $request->saas_appid,
                'technician_id' => $uid
            ])->whereNotIn('orders_id', [$model->orders_id])->whereIn('state', [
                ServiceState::TRAVELING['value'],
                ServiceState::ARRIVAL['value'],
                ServiceState::ING['value']
            ])->count()) {
                throw new \Exception('请先结束上一个服务');
            }
            if ($model->state != ServiceState::ARRIVAL['value']) {
                throw new \Exception('服务状态异常,请刷新查看');
            }
            if ($model->verification != State::YES['value']) {
                throw new \Exception('服务还未核验，请扫码核验');
            }
            if (getHpConfig('service_start_photo', (int)$request->saas_appid, 'orders')) {
                if (!$service_start_photo) {
                    throw new \Exception('请上传开始服务照片');
                }
                $model->service_start_photo = UploadService::path($service_start_photo);
            }
            $model->state = ServiceState::ING['value'];
            $model->service_start_time = date('Y-m-d H:i:s');
            $model->save();
            if ($latitude && $longitude) {
                # 技师
                $MassageUserTechnician = MassageUserTechnician::where(['uid' => $model->technician_id])->find();
                $MassageUserTechnician->latitude = $latitude;
                $MassageUserTechnician->longitude = $longitude;
                $MassageUserTechnician->save();
            }
            $MassageOrders = MassageOrders::where(['id' => $model->orders_id])->find();
            $notice = new Notice();
            $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $model->orders_id])->find();
            $MassageUser = MassageUser::where(['id' => $model->uid])->find();
            $name = $MassageUser->nickname . '(' . $model->uid . ')';
            if ($MassageOrdersAddress) {
                $name = $MassageOrdersAddress['name'] . '(' . $model->uid . ')';
                $notice->addUSER($MassageOrdersAddress->mobile, null);
            }
            $MassageUserWechat = MassageUserWechat::where(['uid' => $model->uid])->find();
            if ($MassageUserWechat) {
                $notice->addUSER(null, $MassageUserWechat->openid);
            }
            $MassageUserT = MassageUser::alias('u')->where(['u.id' => $model->technician_id])
                ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                ->field('u.nickname,u.mobile,uw.openid')
                ->find();
            if ($MassageUserT) {
                $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
            }
            $MassageService = MassageService::where(['id' => $model->service_id])->find();
            $notice->saas_appid = $model->saas_appid;
            $notice->type = NoticeType::SERVICE_START['value'];
            $notice->setData([
                'state' => ServiceState::ING['text'],
                'title' => $MassageService->title,
                'trade' => $MassageOrders->trade,
                'as_id' => $model->id,
                'name' => $name,
                'technician' => $MassageUserT->nickname . '(' . $model->technician_id . ')',
            ]);
            $notice->send();
            Db::commit();
            return $this->success('操作成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function endService(Request $request) {
        $id = $request->post('id');
        $action = $request->post('action');
        $latitude = $request->post('latitude');
        $longitude = $request->post('longitude');
        $service_end_photo = $request->post('service_end_photo');
        $uid = $request->uid;
        try {
            $options = new \stdClass();
            $options->id = $id;
            $options->saas_appid = $request->saas_appid;
            $options->action = $action;
            $options->uid = $uid;
            $options->latitude = $latitude;
            $options->longitude = $longitude;
            if (getHpConfig('service_end_photo', (int)$request->saas_appid, 'orders')) {
                if (!$service_end_photo) {
                    throw new \Exception('请上传结束服务照片');
                }
                $options->service_end_photo = UploadService::path($service_end_photo);
            }
            MassageAppointmentService::endService($options);
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }

        return $this->success('操作成功');
    }
    public function getTechnicianAppointmentService(Request $request) {
        $id = $request->get('id');
        $uid = $request->uid;
        $where = [
            ['id', '=', $id],
            ['saas_appid', '=', $request->saas_appid],
            ['uid', '=', $uid],
            ['state', '=', ServiceState::ING['value']]
        ];
        $model = MassageAppointmentService::where($where)->find();
        if ($model) {
            $technicianAppointmentServic = MassageAppointmentService::where(['technician_id' => $model->technician_id, 'scheduling_id' => $model->scheduling_id])->order('start_time asc')->select();
            $endTime = null;
            $start = false;
            $startTime = null;
            foreach ($technicianAppointmentServic as $item) {
                if ($start) {
                    if ($item->orders_id == $model->orders_id) {
                        $startTime += $item->duration * 60;
                    }
                    if ($item->uid != $model->uid) {
                        $endTime = strtotime($item->start_time);
                        break;
                    }
                }
                if ($item->id == $model->id) {
                    $startTime = strtotime($item->service_start_time) + $item->duration * 60;
                    $start = true;
                }
            }
            # 剩余分钟
            if (!$endTime) {
                $remaining_minutes = 0;
            } else {
                $remaining_minutes = ceil(($endTime - $startTime) / 60);
                if ($remaining_minutes <= 0) {
                    return $this->fail(MassageReplaceIndustryPersonnelName($request->saas_appid, '当前技师已经没有服务时间了'));
                }
            }
            # 获取当前已订购的服务
            /*
            $where = [
                // ['uts.uid', '=', $model->uid],
                // ['uts.saas_appid', '=', $request->saas_appid],

                ['apps.uid', '=', $model->uid],
                ['apps.saas_appid', '=', $request->saas_appid],
                ['apps.orders_id', '=', $model->orders_id],
                [
                    'apps.state',
                    'in',
                    [
                        ServiceState::WAIT_START['value'],
                        ServiceState::TRAVELING['value'],
                        ServiceState::ARRIVAL['value'],
                        ServiceState::ING['value'],
                    ]
                ],
                ['s.overtime_state', '=', State::YES['value']]
            ];
            $field = [
                'apps.id as apps_id',
                's.thumb,s.title,s.overtime_separate,s.overtime_price,s.price,s.tips,s.overtime_duration,s.service_duration,s.overtime_state,s.overtime_separate,s.overtime_duration',
                's.sales_num + s.virtually_sales_num as sales_num'
            ];
            $projects = MassageAppointmentService::alias('apps')->where($where)
                ->join('massage_service s', 's.id=apps.service_id')
                ->field($field)
                ->select();
            $sql = MassageAppointmentService::getLastSql();
            */



            $where = [
                ['uts.uid', '=', $model->uid],
                ['uts.saas_appid', '=', $request->saas_appid],
            ];
            $model = MassageUserTechnicianService::alias('uts')->where($where);
            $projects = $model->join('massage_service ms', 'ms.id = uts.service_id')
                ->field('ms.*,uts.id as uts_id,uts.state,uts.service_id')
                ->select();
            $sql = MassageAppointmentService::getLastSql();



            foreach ($projects as $item) {
                $item->apps_id = $item->service_id;
                $item->thumb = UploadService::url($item->thumb);
                $item->overtime_price = (float)$item->overtime_price;
                $item->price = (float)$item->price;
                $item->num = 0;
            }
            return $this->successRes(['remaining_minutes' => $remaining_minutes, 'sql' => $sql, 'projects' => $projects]);
        }
        return $this->fail('服务不存在或不在服务中');
    }
    public function makePhoneCall(Request $request) {
        $id = $request->post('id');
        $action = $request->post('action');
        $uid = $request->uid;
        $where = [
            ['apps.id', '=', $id],
            ['apps.saas_appid', '=', $request->saas_appid],
            ['apps.state', 'in', [
                ServiceState::WAIT_START['value'],
                ServiceState::TRAVELING['value'],
                ServiceState::ARRIVAL['value'],
                ServiceState::ING['value'],
            ]]
        ];
        if ($action === ActionIdentity::USER['value']) {
            $where[] = ['apps.uid', '=', $uid];
        } else {
            $where[] = ['apps.technician_id', '=', $uid];
        }
        $model = MassageAppointmentService::alias('apps')->where($where)
            ->join('massage_orders_address oa', 'oa.orders_id=apps.orders_id', 'LEFT')
            ->join('massage_user u', 'u.id=apps.uid')
            ->join('massage_user t', 't.id=apps.technician_id')
            ->field('apps.id,u.mobile as user_mobile,oa.mobile as mobile,t.mobile as technician_mobile,oa.province_id,oa.city_id')
            ->find();

        $bindNumberA = $model->mobile;
        if (!$bindNumberA) {
            $bindNumberA = $model->user_mobile;
        }
        $data = [];
        try {
            $winnerlook = getHpConfig('', (int)$request->saas_appid, 'winnerlook');

            if (isset($winnerlook['state']) && $winnerlook['state']) {
                $MassageWinnerlookPrivacy = MassageWinnerlookPrivacy::where(['alias_id' => $model->id])->find();



                if (!$MassageWinnerlookPrivacy) {

                    $MassageWinnerlookPrivacy = MassageWinnerlookPrivacy::getFindNumber($request->saas_appid, WinnerlookChannels::PRIVACY['value'], $model->province_id, $model->city_id);

                    $domain = getHpConfig('domain', (int)$model->saas_appid, 'plugins_domains');
                    $return_url = "{$domain}/app/ycMassage/Notify/winnerlook?appid={$request->saas_appid}";
                    $Yunxin = new Yunxin($request->saas_appid);
                    $data = [
                        'middleNumber' => $MassageWinnerlookPrivacy->tel,
                        'bindNumberA' => $bindNumberA,
                        'bindNumberB' => $model->technician_mobile,
                        'maxBindingTime' => $winnerlook['max_binding_time'],
                        'callbackUrl' => $return_url,
                        // 'customerData'=>"{$request->saas_appid}-{}"
                    ];
                    $Yunxin->middleNumberAXB($data);
                    $MassageWinnerlookPrivacy->alias_id = $model->id;
                    $MassageWinnerlookPrivacy->bind_number_a = $bindNumberA;
                    $MassageWinnerlookPrivacy->bind_number_b = $model->technician_mobile;
                    $MassageWinnerlookPrivacy->state = WinnerlookState::BINDING['value'];
                    $MassageWinnerlookPrivacy->unbind_time = date('Y-m-d H:i:s', time() + $winnerlook['max_binding_time']);
                    $MassageWinnerlookPrivacy->save();
                }
                $data['mobile'] = $MassageWinnerlookPrivacy->tel;
            } else {
                if ($action === ActionIdentity::USER['value']) {
                    $data['mobile'] = $model->technician_mobile;
                } else {
                    $data['mobile'] = $bindNumberA;
                }
            }
            return $this->successRes($data);
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
    }
}
